package com.jlcloud.core.boot.request;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import com.jlcloud.core.tool.utils.WebUtil;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PatternMatchUtils;

import java.io.IOException;
import java.util.List;

/**
 * Request全局过滤
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
@AllArgsConstructor
public class JlCloudRequestFilter implements Filter {

	/**
	 * 请求配置
	 */
	private final RequestProperties requestProperties;
	/**
	 * 路径匹配
	 */
	private final AntPathMatcher antPathMatcher = new AntPathMatcher();

	/**
	 * 默认拦截路径
	 */
	private final List<String> defaultBlockUrl = List.of("/**/actuator/**", "/health/**");
	/**
	 * 默认白名单
	 */
	private final List<String> defaultWhiteList = List.of("127.0.0.1", "172.*.*.*", "192.*.*.*", "10.*.*.*", "0:0:0:0:0:0:0:1");
	/**
	 * 默认提示信息
	 */
	private final static String DEFAULT_MESSAGE = "当前请求未完成，请联系管理员！";

	@Override
	public void init(FilterConfig config) {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// 获取请求
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		// 判断 拦截请求 与 白名单
		if (requestProperties.getEnabled()) {
			// 获取请求路径
			String path = httpRequest.getServletPath();
			// 获取请求IP
			String ip = WebUtil.getIP(httpRequest);
			// 判断是否拦截请求
			if (isRequestBlock(path, ip)) {
				throw new ServletException(DEFAULT_MESSAGE);
			}
			// 判断是否跳过Request包装
			if (isRequestSkip(path)) {
				chain.doFilter(request, response);
			}
			// 采用Request包装
			else {
				JlCloudHttpServletRequestWrapper jlcloudRequest = new JlCloudHttpServletRequestWrapper(httpRequest);
				chain.doFilter(jlcloudRequest, response);
			}
		}
		// 采用原版Request请求
		else {
			chain.doFilter(request, response);
		}
	}

	/**
	 * 是否白名单
	 *
	 * @param ip ip地址
	 * @return boolean
	 */
	private boolean isWhiteList(String ip) {
		List<String> whiteList = requestProperties.getWhiteList();
		String[] defaultWhiteIps = defaultWhiteList.toArray(new String[0]);
		String[] whiteIps = whiteList.toArray(new String[0]);
		return PatternMatchUtils.simpleMatch(defaultWhiteIps, ip) || PatternMatchUtils.simpleMatch(whiteIps, ip);
	}

	/**
	 * 是否黑名单
	 *
	 * @param ip ip地址
	 * @return boolean
	 */
	private boolean isBlackList(String ip) {
		List<String> blackList = requestProperties.getBlackList();
		String[] blackIps = blackList.toArray(new String[0]);
		return PatternMatchUtils.simpleMatch(blackIps, ip);
	}

	/**
	 * 是否禁用请求访问
	 *
	 * @param path 请求路径
	 * @return boolean
	 */
	private boolean isRequestBlock(String path) {
		List<String> blockUrl = requestProperties.getBlockUrl();
		return defaultBlockUrl.stream().anyMatch(pattern -> antPathMatcher.match(pattern, path)) ||
			blockUrl.stream().anyMatch(pattern -> antPathMatcher.match(pattern, path));
	}

	/**
	 * 是否拦截请求
	 *
	 * @param path 请求路径
	 * @param ip   ip地址
	 * @return boolean
	 */
	private boolean isRequestBlock(String path, String ip) {
		return (isRequestBlock(path) && !isWhiteList(ip)) || isBlackList(ip);
	}

	/**
	 * 是否跳过请求包装
	 *
	 * @param path 请求路径
	 * @return boolean
	 */
	private boolean isRequestSkip(String path) {
		return requestProperties.getSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path));
	}

	@Override
	public void destroy() {

	}

}
